package com.cke.yang.security.infra.handler;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * @author yuyang
 */
@Slf4j
@Component
public class BaseLoginInvalidHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        log.error("认证失败", authException);
        String detailMessage = StringUtils.hasLength(authException.getMessage()) ? authException.getMessage() : "认证失效，请先登录";
        response.getWriter().write("{\"code\":401,\"msg\":\"" +detailMessage + "\"}");
    }

}
